﻿using System;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
using System.Web;

namespace Wedn.Core.Utility
{
    /// <summary>
    /// 客户端请求操作助手类
    /// </summary>
    public class RequestHelper
    {
        /// <summary>
        /// 判断当前页面是否接收到了Post请求
        /// </summary>
        /// <returns></returns>
        public static bool IsPost
        {
            get
            {
                return HttpContext.Current.Request.HttpMethod.Equals("POST");
            }
        }

        /// <summary>
        /// 判断当前页面是否接收到了Get请求
        /// </summary>
        /// <returns></returns>
        public static bool IsGet
        {
            get
            {
                return HttpContext.Current.Request.HttpMethod.Equals("GET");
            }
        }

        /// <summary>
        /// 返回当前页面是否是跨站提交
        /// </summary>
        /// <returns></returns>
        public static bool IsCrossSitePost
        {
            get
            {
                if (IsPost)
                {
                    if (UrlReferrer.Length < 7)
                    {
                        return true;
                    }
                    Uri u = new Uri(UrlReferrer);
                    return u.Host != Host;
                }
                return false;
            }
        }

        /// <summary>
        /// 得到主机头
        /// </summary>
        /// <returns></returns>
        public static string Host
        {
            get
            {
                return HttpContext.Current.Request.Url.Host;
            }
        }

        public static bool ExistsQuery(string strName)
        {
            HttpRequest request = HttpContext.Current.Request;
            if (request.QueryString.Count == 0)
                return false;
            string req = request.QueryString.ToString();
            if (!req.Contains(strName))
                return false;
            return true;
        }

        /// <summary>
        /// 获得指定Url参数的值
        /// </summary>
        /// <param name="strName">Url参数</param>
        /// <returns>Url参数的值</returns>
        public static string QueryString(string strName)
        {
            return QueryString(strName, false);
        }

        /// <summary>
        /// 获得指定Url参数的值
        /// </summary>
        /// <param name="strName"></param>
        /// <param name="isLower">是否转化成小写</param>
        /// <returns></returns>
        public static string QueryString(string strName, bool isLower)
        {
            string temp = HttpContext.Current.Request.QueryString[strName];
            if (temp == null)
                return string.Empty;
            if (isLower)
                return StringHelper.UrlDecode(temp.ToLower());
            return StringHelper.UrlDecode(temp);
        }

        /// <summary>
        /// 获得指定Url参数的int类型值
        /// </summary>
        /// <param name="strName">Url参数</param>
        /// <returns>Url参数的int类型值</returns>
        public static int QueryInt(string strName)
        {
            return StringHelper.StrToInt(HttpContext.Current.Request.QueryString[strName], 0);
        }

        /// <summary>
        /// 获得指定Url参数的int类型值
        /// </summary>
        /// <param name="strName">Url参数</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>Url参数的int类型值</returns>
        public static int QueryInt(string strName, int defValue)
        {
            return StringHelper.StrToInt(HttpContext.Current.Request.QueryString[strName], defValue);
        }

        /// <summary>
        /// 获得指定表单参数的值
        /// </summary>
        /// <param name="strName">表单参数</param>
        /// <returns>表单参数的值</returns>
        public static string FormString(string strName)
        {
            string str = HttpContext.Current.Request.Form[strName];
            if (str == null)
                return string.Empty;
            return str;
        }

        /// <summary>
        /// 请求页面类型
        /// </summary>
        public static PageType QueryType
        {
            get
            {
                string rurl = HttpContext.Current.Request.RawUrl.Replace(Config.SiteUrl.TrimEnd('/'), string.Empty).ToLower();
                if (string.IsNullOrEmpty(rurl))
                    return PageType.Default;
                if (rurl.Contains("post=") || rurl.Contains("/post/"))
                    return PageType.Post;
                if (rurl.Contains("cate=") || rurl.Contains("/category/"))
                    return PageType.Category;
                if (rurl.Contains("tag=") || rurl.Contains("/tag/"))
                    return PageType.Tag;
                if (rurl.Contains("arch=") || rurl.Contains("/archive/"))
                    return PageType.Archive;
                if (rurl.Contains("page=") || rurl.Contains("/page/"))
                    return PageType.Page;
                return PageType.Default;
            }
        }

        /// <summary>
        /// 获得指定表单参数的int类型值
        /// </summary>
        /// <param name="strName">表单参数</param>
        /// <param name="defValue">缺省值</param>
        /// <returns>表单参数的int类型值</returns>
        public static int FormInt(string strName, int defValue)
        {
            return StringHelper.StrToInt(HttpContext.Current.Request.Form[strName], defValue);
        }

        /// <summary>
        /// 客户端IP地址
        /// </summary>
        public static string IPAddress
        {
            get
            {
                string result = String.Empty;
                result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (null == result || result == String.Empty)
                    result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                if (null == result || result == String.Empty)
                    result = HttpContext.Current.Request.UserHostAddress;
                if (null == result || result == String.Empty || !StringHelper.IsIP(result))
                    return "0.0.0.0";
                return result;
            }
        }

        /// <summary> 
        /// 获得当前URL(重写前)
        /// 中文编码问题，默认页问题
        /// </summary>
        public static string CurrentUrl
        {
            get
            {
                return "http://" + HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.RawUrl;
            }
        }

        /// <summary>
        /// 获取有关客户端上次请求的 URL 的信息，该请求链接到当前的 URL。
        /// </summary>
        public static string UrlReferrer
        {
            get
            {
                return Convert.ToString(HttpContext.Current.Request.UrlReferrer);
            }
        }

        private static readonly Regex MOBILE_REGEX = new Regex(@"(nokia|sonyericsson|blackberry|iphone|samsung|sec\-|windows ce|motorola|mot\-|up.b|midp\-)", RegexOptions.IgnoreCase | RegexOptions.Compiled);
        /// <summary>
        /// 是否是手机浏览
        /// opera没搞定
        /// </summary>
        public static bool IsMobile
        {
            get
            {
                HttpContext context = HttpContext.Current;
                if (context != null)
                {
                    HttpRequest request = context.Request;
                    string useragent = request.UserAgent;
                    string accept = request.ServerVariables["HTTP_ACCEPT"];
                    if (!string.IsNullOrEmpty(accept) && accept.IndexOf("wap") > 0)
                        return true;
                }

                return false;
            }
        }

        /// <summary>
        /// 返回客户端浏览器版本
        /// 如果是IE类型，返回版本数字
        /// 如果不是IE类型，返回-1
        /// </summary>
        /// <returns>一位数字版本号</returns>
        public static int GetClientBrowserVersion()
        {
            string USER_AGENT = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"];

            if (USER_AGENT.IndexOf("MSIE") < 0) return -1;

            string version = USER_AGENT.Substring(USER_AGENT.IndexOf("MSIE") + 5, 1);
            int res;
            if (int.TryParse(version, out res))
                return res;
            return -1;
        }

        /// <summary>
        /// 判断是否来自搜索引擎链接
        /// </summary>
        /// <returns>是否来自搜索引擎链接</returns>
        public static bool IsSearchEngine
        {
            get
            {
                if (HttpContext.Current.Request.UrlReferrer == null)
                    return false;

                string[] SearchEngine = { "google", "yahoo", "msn", "baidu", "sogou", "sohu", "sina", "163", "lycos", "tom", "yisou", "iask", "soso", "gougou", "zhongsou" };
                string tmpReferrer = HttpContext.Current.Request.UrlReferrer.ToString().ToLower();
                for (int i = 0; i < SearchEngine.Length; i++)
                {
                    if (tmpReferrer.IndexOf(SearchEngine[i]) >= 0)
                        return true;
                }
                return false;
            }
        }
    }

    /// <summary>
    /// 页面类型
    /// </summary>
    public enum PageType
    {
        /// <summary>
        /// 默认页
        /// </summary>
        Default,
        /// <summary>
        /// 文章页
        /// </summary>
        Post,
        /// <summary>
        /// 类别页
        /// </summary>
        Category,
        /// <summary>
        /// 标签页
        /// </summary>
        Tag,
        /// <summary>
        /// 归档页
        /// </summary>
        Archive,
        /// <summary>
        /// 分页
        /// </summary>
        Page
    }
}